package eclipse.lib.sound;
import javax.sound.midi.*;
import eclipse.*;
import eclipse.util.*;
public class MidiPlayer extends ThreadedTimer
{
	private Sequencer 	midiSequencer;
	public MidiPlayer()
	{
		initMidiPlayer();
	}
	public MidiPlayer(ERL eFile)
	{
		initMidiPlayer();
		loadMidi(eFile);
	}
	private void initMidiPlayer()
	{
		try
		{
			setName("Midi Player");
			midiSequencer = MidiSystem.getSequencer();
			setEnabled(true);
			setInterval(1000);
			start();
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
	public void loadMidi(ERL eFile)
	{
		try
		{
			midiSequencer.setSequence(eFile.openStream());
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
	public void loopMidi()
	{
		if(midiSequencer == null)
			return;
		if(midiSequencer.isOpen() || midiSequencer.isRunning())
			return;		
		try
		{
			midiSequencer.setLoopCount(Integer.MAX_VALUE);			
			midiSequencer.open();
			midiSequencer.start();
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
	public void playMidi()
	{
		if(midiSequencer == null)
			return;
		if(midiSequencer.isOpen() || midiSequencer.isRunning())
			return;		
		try
		{
			midiSequencer.open();
			midiSequencer.start();
		}
		catch(Exception e)
		{
			ErrorManager.handleError(e);
		}
	}
    public void stopMidi()
    {
    	if(!midiSequencer.isOpen() || !midiSequencer.isRunning())
    		return;
    	midiSequencer.stop();
    	midiSequencer.close();
    }
	public void tick() 
	{
		if(midiSequencer == null)		
			return;		
		if(!midiSequencer.isOpen())
			return;
		while(midiSequencer.isRunning())
			Sleep(300);
		stopMidi();		
	}		
}

